package server

import (
	"context"
	"math/rand"
	"strconv"
	"time"
	"weekly2/pkg"
	"weekly2/rpc/initiate"
	"weekly2/rpc/model"
	"weekly2/rpc/proto/user"
)

func Register(in *user.RegisterReq) (*user.RegisterResp, error) {
	u := model.User{
		Phone:    in.Phone,
		Password: pkg.Md5Password(in.Password),
	}
	err := initiate.DB.Where("phone =?", u.Phone).Find(&u).Error
	if u.ID != 0 {
		return &user.RegisterResp{Greet: "当前账号已经被注册请前往登录"}, err
	}
	if err != nil {
		return &user.RegisterResp{Greet: "注册失败"}, err
	}
	return &user.RegisterResp{Greet: "注册成功"}, nil
}

func Login(in *user.LoginReq) (*user.LoginResp, error) {
	u := model.User{
		Phone:    in.Phone,
		Password: pkg.Md5Password(in.Password),
	}
	err := initiate.DB.Where("phone =?", u.Phone).Find(&u).Error
	if err != nil {
		return &user.LoginResp{Greet: "登录失败"}, err
	}
	/*	pkg.NewJWT("2209a").CreateToken()*/
	return &user.LoginResp{Greet: "登录成功"}, err
}

func SendSms(in *user.SendSmsReq) (*user.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000
	/*send, err := pkg.Send("sms"+in.Phone, strconv.Itoa(code))
	if err != nil {
		return &user.SendSmsResp{Code: "验证码接收不到"}, nil
	}
	if *send.Body.Code != "OK" {
		return nil, errors.New(*send.Body.Message)
	}*/
	initiate.Client.Set(context.Background(), "Sms"+in.Phone, code, time.Minute*3)
	return &user.SendSmsResp{Code: strconv.Itoa(code)}, nil
}
